class FlyLine extends egret.Sprite {

    speedRate = 7; // 速度
    gravity: number = 100; // 重力   
    flyingBird: any; // 飞翔的小鸟
    flyRad : any; // 弧度

    startPX:number = 0;
	startPY:number = 0;
	sWidth:number = Const.SCENT_WIDTH;
	sHeight:number = Const.SCENT_HEIGHT;

    GameScene : any

	fadeCnt = 0
	startX = 0;

    flySpeed = Const.SPEED * (Math.random() * 0.2 + 0.8) * this.speedRate;
	halfflyHeight = 60;
	//downmask = new egret.Rectangle(0,0,200,this.halfflyHeight); //飞行物的高度

    public constructor() {
        super();
    }    

    private create(): void{
        this.flyRad = this.angleToRad(this.GameScene.angle)
		this.flyingBird = new MoveClipSpriteSheet("jjfly_json",5, true);
        this.flyingBird.x = 105;
        this.flyingBird.y = 105;
		this.flyingBird.mask = this.GameScene.penguinmask;
        this.addChild(this.flyingBird);

		let rect = new egret.Shape();
		rect.graphics.beginFill(0xff0000);
		rect.graphics.drawRect(0,0,460,40);
		rect.graphics.endFill();
		rect.x = 200;
		rect.y = 790;
		//this.addChild(rect);
		//this.addLongTrace(0, 10, 1);
        this.startFly();
    }

    public setGameScene(gameScene:any): void{
        this.GameScene = gameScene;
        this.create();
    }

    private startFly(): void{
		this.stopFly()
        egret.startTick(this.clock,this);
    }

    private stopFly():void{
        egret.stopTick(this.clock,this);
    }

    timeParam = 0;
    private clock(timeSpan:number):boolean{        
        this.timeParam += 0.6/Const.FPS
        this.moveBrid(this.flySpeed,this.flyRad)
		if(!this.flyingBird.hasdraw())
			this.flyingBird.gotoAndPlay(0);
		this.flyingBird.render(10);
        return false;
    }

    private stateMove(distance, totalDistance){

    }

	private stageMove(difDistance:number, totalDistance:number){
		var event = new StageMove(StageMove.Move,true)
		event.distance = difDistance;
		event.totalDistance = totalDistance;
		this.dispatchEvent(event);
	}

	tween : any;
	hitOffsetY: any;
    private moveBrid(speed,rad){
		let offsetX:number = this.GameScene.penguinOffsetX;
		let offsetY:number = Const.SCENT_HEIGHT - this.GameScene.floorLine + this.GameScene.penguinHeight/2;
		let flyStageDistance:number = this.GameScene.visibleDistance;
		let fadeCne:number = 0;
		if(this.hitOffsetY == null)
			this.hitOffsetY = this.GameScene.floorLine - this.GameScene.penguin.y - this.GameScene.penguinHeight/2;
        let g:number = 9.8 * this.gravity
        var x = speed * Math.cos(rad) * this.timeParam;
		var y = speed * Math.sin(rad) * this.timeParam - 1/2 * g * this.square(this.timeParam) + this.hitOffsetY;//v0*sina-1/2gt2
		var vy = speed * Math.sin(rad) - g * this.timeParam;
		var vx = speed * Math.cos(rad);//x轴上的运动速度			
		var slope = -g / this.square(speed) / this.square(Math.cos(rad)) * x + Math.sin(rad) / Math.cos(rad);//抛物线斜率					
		this.flyingBird.rotation = slope * this.GameScene.angle;

		var dif = vx * 1/Const.FPS;
		if(x + this.startPX > flyStageDistance){	
			this.stageMove(dif, x + this.startPX);//舞台一个时间间隔内移动的距离
		}else{
			this.flyingBird.x =  this.sWidth - offsetX - (x + this.startPX);	
		}
		this.flyingBird.y =  this.sHeight - offsetY - y;
		//console.log("this.flyingBird.x "+this.flyingBird.x);
		
		let downdis = this.GameScene.floorLine - this.flyingBird.y
		
		if(y <= 0 && slope < 0){		
			//reset				
			this.timeParam = 0;
			this.startPX += x;
			this.startPY = 0;
			this.flySpeed = speed * 2.6 / 3;
			this.flyRad = rad * 2.6 / 3;
			this.fadeCnt ++ ;
			
			this.stopFly();
			this.hitOffsetY = 0;
			if(Math.abs(this.flyingBird.rotation) >= 46 && this.fadeCnt == 1){
				//角度太大，请它倒立
				this.turnDown(this.flyingBird.x, this.flyingBird.y, "down");
				this.stopFly();
				this.gameOver(this.startPX);
				return;
			}
			if(this.fadeCnt == 3){
				//end game
				this.stopFly();
				//添加长划痕
				var slideTime = Math.cos(rad) * 800;		
				this.addLongTrace(x, dif, slideTime);
			}else{
				this.tween = egret.Tween.get(this.flyingBird, {loop:false})
				.to({rotation:this.flyRad}, 50, egret.Ease.bounceOut)
				.call(function(){
					this.startFly();
					egret.Tween.removeTweens(this.tween);
					//添加痕迹
					this.addTrace(dif);
				},this);
			}
			this.refreshScore(this.startPX);
		}
		else
		{
			//console.log("refreshScore Math.cos(rad)= " +Math.cos(rad) + "x="+x+" this.timeParam="+this.timeParam);
			this.refreshScore(x + this.startPX);
		}
    }

	private addTrace(dif){
		console.log("addTrace");
		let totalD = 0;
		let tracer = Common.createBitmapByName("traces_png");
		tracer.width = 100
		tracer.x = this.flyingBird.x -(tracer.width - this.GameScene.penguinWidth)/2 ;
		tracer.y = this.GameScene.floorLine - tracer.height/2;
		this.addChild(tracer);

		//tracer.x += dif;

		let downdis = this.GameScene.floorLine - this.flyingBird.y

        egret.startTick(tracerClock,this);
		function tracerClock(){
			tracer.x += dif;
			totalD += dif;
			if(totalD > this.sWidth * 2 / 3){
				//console.log("回收痕迹");
				egret.stopTick(tracerClock,this);
				this.removeChild(tracer);
			}
			return false;
		}
	}

	longTracer : egret.Bitmap;
	masklength = 0;
	downbird : any;
	private addLongTrace(xPass,dif,TimeC){
		this.downbird = new MoveClipSpriteSheet("jjflyend_json",2, false);
		this.downbird.gotoAndPlay(0);
		this.downbird.x = this.flyingBird.x;
		this.downbird.y = this.flyingBird.y;
		this.downbird.mask = this.GameScene.penguinmask;
		this.removeChild(this.flyingBird);
		this.addChild(this.downbird);
		this.longTracer = Common.createBitmapByName("traces_png");
		this.addChild(this.longTracer);
		this.longTracer.width = 700;
		this.longTracer.height = 10;
		this.longTracer.x = this.flyingBird.x - this.longTracer.width;
		this.longTracer.y = this.GameScene.floorLine - this.longTracer.height/2;
		let maskrect = new egret.Rectangle(this.longTracer.width-this.masklength,0,this.masklength,this.longTracer.height)
		this.longTracer.mask = maskrect;
        egret.startTick(longTracerClock,this);

		function longTracerClock(){
			//console.log("longTracerClock add" + dif);
			this.longTracer.x += dif;
			this.masklength += dif;
			let maskrect = new egret.Rectangle(this.longTracer.width-this.masklength,0,this.masklength,this.longTracer.height)
			this.longTracer.mask = maskrect;
			this.stageMove(dif, xPass + this.startX + 432);
			this.refreshScore(this.GameScene.score + dif);
			return false;
		}

		function Timeout(){
        	egret.stopTick(longTracerClock,this);

			let tracer = Common.createBitmapByName("traces_png");
			tracer.width = 100
			tracer.x = this.flyingBird.x -(tracer.width - this.GameScene.penguinWidth)/2 ;
			tracer.y = this.GameScene.floorLine - tracer.height/2;
			this.addChild(tracer);
			
			this.swapChildren(this.downbird,tracer)

			let result=xPass + this.startX + 432;
			this.gameOver(xPass + this.startX + 432)
			//console.log("downbird masklength=" + this.masklength);
		}
		
        var timer:egret.Timer = new egret.Timer(TimeC,1);
        timer.addEventListener(egret.TimerEvent.TIMER_COMPLETE,Timeout,this);
        timer.start();
	}

	private gameOver(distance:number){
		var event = new GameOver(GameOver.OVER,true)
		event.distance = distance;
		event.x = this.flyingBird.x;
		this.dispatchEvent(event);
	}

	private refreshScore(distance:number){
		this.GameScene.score = distance;
		this.GameScene.scoretext.text = "得分："+ Math.floor(distance);
	}

	private turnDown(fx, fy, status){
		this.flyingBird.visible = false
		this.GameScene.onShootEnd(fx,fy);
	}

	private square(num:number){
		return num*num;
	}

    private angleToRad(angle){
        return Math.PI / 180 * angle
    }
}
